<template>
    <!-- 供应商新增/修改界面 -->
    <div class="white-container">
      <el-form 
        :model="supplierForm" 
        :rules="rules"
        ref="formRef" 
        class="grid-container"
        label-width="120px"
      >
        <h2 class="section-header">供应商{{ isEdit ? '编辑' : '新增' }}</h2>
        
        <el-row :gutter="20"> <!-- 使用栅格系统 -->
            <el-col :span="12">
                <el-form-item label="编码" prop="sup_code">
                    <el-input 
                    v-model="supplierForm.sup_code" 
                    placeholder="自动获取系统编码" 
                    disabled
                    style="width: 100%"
                    ></el-input>
                </el-form-item>
            </el-col>
          
          <el-col :span="12">
            <el-form-item label="名称" prop="sup_name">
              <el-input v-model="supplierForm.sup_name" placeholder="请输入" style="width: 100%"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="行业" prop="sup_industry">
              <el-select 
                v-model="supplierForm.sup_industry" 
                placeholder="请选择"
                style="width: 100%"
              >
                <el-option 
                  v-for="dept in Industrydata" 
                  :key="dept.dict_code" 
                  :label="dept.dict_label" 
                  :value="dept.dict_label" 
                />
              </el-select>
            </el-form-item>
          </el-col>
          
          <el-col :span="12">
            <el-form-item label="分类" prop="sup_type">
              <el-select 
                v-model="supplierForm.sup_type" 
                placeholder="请选择"
                style="width: 100%" 
              >
                <el-option 
                  v-for="dept in Classifydata" 
                  :key="dept.dict_code" 
                  :label="dept.dict_label" 
                  :value="dept.dict_label" 
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="联系人" prop="sup_linkman">
              <el-input v-model="supplierForm.sup_linkman" placeholder="请输入" style="width: 100%"></el-input>
            </el-form-item>
          </el-col>
          
          <el-col :span="12">
            <el-form-item label="电话" prop="sup_linkphone">
              <el-input v-model="supplierForm.sup_linkphone" placeholder="请输入" style="width: 100%"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="邮箱" prop="sup_email">
              <el-input v-model="supplierForm.sup_email" placeholder="请输入" style="width: 100%"></el-input>
            </el-form-item>
          </el-col>
          
          <el-col :span="12">
            <el-form-item label="部门" prop="sup_depId">
              <el-select 
                v-model="supplierForm.sup_depId" 
                placeholder="请选择"
                style="width: 100%" 
              >
                <el-option 
                  v-for="dept in Departmentdata" 
                  :key="dept.department_id" 
                  :label="dept.department_name" 
                  :value="dept.department_id" 
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="负责人" prop="sup_userId">
              <el-select 
                v-model="supplierForm.sup_userId" 
                placeholder="请选择"
                style="width: 100%" 
              >
                <el-option 
                  v-for="dept in Userdata" 
                  :key="dept.user_id" 
                  :label="dept.user_name" 
                  :value="dept.user_id" 
                  :data-deptid="dept.department_id"
                />
              </el-select>
            </el-form-item>
          </el-col>
          
          <el-col :span="12">
            <el-form-item label="状态" prop="sup_status">
              <el-radio-group v-model="supplierForm.sup_status">
                <el-radio :label="0">启用</el-radio>
                <el-radio :label="1">停用</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item label="地址" prop="sup_address">
              <div style="display: flex; align-items: center;">
                <el-input v-model="supplierForm.sup_address" placeholder="请输入" style="width: 100%"></el-input>
                <el-button type="primary" @click="searchAddress" style="margin-left: 10px;">定位</el-button>
              </div>
            </el-form-item>
          </el-col>
        </el-row>
        
        <!-- 添加地图容器 -->
        <el-row :gutter="20">
          <el-col :span="24">
            <div id="container" style="height: 300px; width: 1000px; margin-bottom: 20px;margin-left: auto;"></div>
          </el-col>
        </el-row>
        
        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item label="备注" prop="remark">
              <el-input
                v-model="supplierForm.remark"
                type="textarea"
                :rows="4"
                placeholder="请输入备注信息"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </div>
  
    <!-- 财务信息 -->
    <div class="white-container">
      <el-form 
        :model="supplierForm" 
        :rules="rules"
        ref="financeFormRef" 
        class="grid-container"
        label-width="120px" 
      >
        <h2 class="section-header">财务信息</h2>
        
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="账户" prop="sup_accountName">
              <el-input v-model="supplierForm.sup_accountName" placeholder="请输入" style="width: 100%"></el-input>
            </el-form-item>
          </el-col>
          
          <el-col :span="12">
            <el-form-item label="税号" prop="sup_taxpayerNum">
              <el-input v-model="supplierForm.sup_taxpayerNum" placeholder="请输入" style="width: 100%"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="银行账号" prop="sup_bankAccount">
              <el-input v-model="supplierForm.sup_bankAccount" placeholder="请输入" style="width: 100%"></el-input>
            </el-form-item>
          </el-col>
          
          <el-col :span="12">
            <el-form-item label="开户银行" prop="sup_openBank">
              <el-input v-model="supplierForm.sup_openBank" placeholder="请输入" style="width: 100%"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item label="开户行地址" prop="sup_openBankAddress">
              <el-input v-model="supplierForm.sup_openBankAddress" placeholder="请输入" style="width: 100%"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </div>
  
    <!-- 在上传附件部分添加文件输入 -->
    <div class="white-container">
      <div class="grid-container">
        <h2 class="section-header">上传附件</h2>
        <!-- 文件选择器 -->
        <input 
          type="file" 
          multiple 
          @change="handleFileUpload"
          ref="fileInput"
          style="display: none"
        />
        <div class="upload-section">
          <el-upload
            :file-list="filelist" 
            class="upload-demo"
            action="http://localhost:5194/api/PublicFile/Uploadfile"
            multiple
            name="files"
            :on-preview="handlePreview"
            :on-remove="handleRemove"
            :limit="3"
            :on-exceed="handleExceed"
            :on-success="handleFileSuccess"
            :headers="headers"
            style="text-align: left;margin-left: 20px;">
            <el-button type="primary">上传附件</el-button>
                <template #tip>
                  <span class="upload-tips">
                    您可以上传doc, pdf, rar等格式的文件，单个文件上传最大200MB。
                  </span>
                </template>
        </el-upload>
        </div>
      </div>
    </div>

    <!-- 底部操作栏 -->
    <div class="action-bar">
        <button class="action-btn btn-close" @click="jump">关闭</button>
        <button v-if="!isEdit"  class="action-btn btn-save-add" @click="addSupplier(true)">保存并新增</button>
        <button class="action-btn btn-save" @click="save()">保存</button>
    </div>
  </template>
  
<script>
import { useRouter, useRoute } from 'vue-router'
import {ref,reactive,onMounted,onUnmounted} from 'vue';
import http from '../auth/index';
import { ElMessage,ElMessageBox  } from 'element-plus'; //提示信息
export default {
    setup(){
        const router = useRouter();

        const formRef = ref();      // 基础信息表单引用
        const financeFormRef = ref(); // 财务信息表单引用

        // 在 setup 中定义响应式数据
        const fileInput = ref(null); // 文件输入引用
        
        // 安全获取 route 对象
        let route;
        try {
            route = useRoute();
        } catch (e) {
            console.error("无法获取路由对象:", e);
            route = { query: {} }; // 创建默认空对象
        }
        
        // 安全获取 id 参数
        const id = ref(route.query ? route.query.id || null : null);
        const isEdit = ref(!!id.value);
        
        // 响应式表单模型
        const supplierForm = reactive({
            sup_code: "",
            sup_name: "",
            sup_industry: "",
            sup_type: "",
            sup_linkman: "",
            sup_linkphone: "",
            sup_email: "",
            sup_depId: null,
            sup_userId: null,
            sup_status: 0,
            sup_address: "",
            remark: "",
            sup_accountName: "",
            sup_taxpayerNum: "",
            sup_bankAccount: "",
            sup_openBank: "",
            sup_openBankAddress: "",
            create_name: "" // 将从sessionStorage获取
        }); 

        //#region 上传附件
        const filelist = ref([])
        //头部带token
        const token=sessionStorage.getItem('token');
        const headers = {
             Authorization: `Bearer ${token}`, // 添加 token 到请求头
        };
        // 上传成功回调方法
        function handleFileSuccess(response, file, fileList) {
            if (Array.isArray(response)) {
                // 创建 { 文件名: URL } 的映射
                const urlMap = response.reduce((map, res) => {
                    if (res.success) map[res.originalName] = res.path;
                    return map;
                }, {});
                
                // 更新文件列表
                filelist.value = fileList.map(item => ({
                    ...item,
                    url: urlMap[item.name] || item.url,  // 优先使用新URL
                    status: urlMap[item.name] ? 'success' : item.status,
                    originalName: item.originalName || item.name
                }));
            }
        }
        //预览
        function handlePreview(file){
            if (!file.url) {
                ElMessage.error('文件URL不存在，请重新上传');
                return;
            }
            const ext = file.name.split('.').pop().toLowerCase();
            
            switch (ext) {
                case 'jpg': case 'jpeg': case 'png': case 'gif': case 'bmp':
                    window.open(file.url, '_blank');
                    break;
                case 'pdf':
                    window.open(file.url, '_blank');
                    break;
                case 'doc': case 'docx': case 'xls': case 'xlsx': case 'ppt': case 'pptx':
                    window.open(file.url, '_blank');
                    break;
                default:
                    // 下载其他格式文件
                    const link = document.createElement('a');
                    link.href = file.url;
                    link.download = file.name;
                    document.body.appendChild(link);
                    link.click();
                    document.body.removeChild(link);
            }
        };

        //移除附件
        function handleRemove(file, fileList) {
            filelist.value = fileList;
        }

        // 查询货品附件
        function GetPurchaseFileByCode(sup_code) {
          http.get("/PublicFile/GetPublicFileBy?type=供应商&code=" + sup_code)
            .then(res => {
              filelist.value = res.data.map(item => {
                return {
                  name: item.title,
                  url: item.file_name,
                  originalName: item.title
                }
              })
            })
        }
        //#endregion

        // 新增供应商方法
        const addSupplier = async (resetAfterSave = false) => {
        try {
            const user = JSON.parse(sessionStorage.getItem("user"));
            
            // 获取自动生成编号 供应商编号为2
            const GeneratedCode = async () => {
                const res = await http.get("/CodeRule/GeneratedCode?id=2");
                supplierForm.sup_code = res.data;
            };

            const resetForm = () => {
              // 重置基础表单
              formRef.value?.resetFields();
              // 重置财务表单
              financeFormRef.value?.resetFields();
              
              // 手动重置状态（因为resetFields不会重置radio）
              supplierForm.sup_status = 0;
              
              // 重置其他需要清空的字段
              supplierForm.sup_code = "";
              supplierForm.create_name = JSON.parse(sessionStorage.getItem("user"))?.name || "";
            };

            // 首先执行生成编号
            await GeneratedCode();
            
            // 根据选择的ID查找对应的名称
            const deptObj = Departmentdata.value.find(item => item.department_id === supplierForm.sup_depId);
            const userObj = Userdata.value.find(item => item.user_id === supplierForm.sup_userId);

            // 构造符合后端要求的DTO对象
            const addSupplierDto = {
                sup_code: supplierForm.sup_code,
                sup_name: supplierForm.sup_name,
                sup_industry: supplierForm.sup_industry, // 获取行业名称
                sup_type: supplierForm.sup_type, // 获取分类名称
                sup_linkman: supplierForm.sup_linkman,
                sup_linkphone: supplierForm.sup_linkphone,
                sup_email: supplierForm.sup_email,
                sup_depId: supplierForm.sup_depId,
                sup_depName: deptObj ? deptObj.department_name : "", // 获取部门名称
                sup_userId: supplierForm.sup_userId,
                sup_userName: userObj ? userObj.user_name : "", // 获取用户名称
                sup_status: supplierForm.sup_status,
                sup_address: supplierForm.sup_address,
                remark: supplierForm.remark,
                sup_accountName: supplierForm.sup_accountName,
                sup_taxpayerNum: supplierForm.sup_taxpayerNum,
                sup_bankAccount: supplierForm.sup_bankAccount,
                sup_openBank: supplierForm.sup_openBank,
                sup_openBankAddress: supplierForm.sup_openBankAddress,
                create_name: user?.name || "系统管理员"
            };

            // 发送新增请求
            const res = await http.post('/Supplier/AddSupplier', addSupplierDto);
                //7.附件上传
                if (filelist.value.length > 0) {
                  filelist.value.forEach(file => {
                    http.post("/PublicFile/AddFile?type=供应商&code=" + supplierForm.sup_code + "&file=" + file.url+"&title="+file.originalName)
                  });
                }
                
                // 处理响应
                if (res.data > 0) {
                    ElMessage.success('新增成功');
                    if (resetAfterSave) {
                      // 重置表单
                      resetForm();
                    } else {
                      router.push('supplier');
                    }
                } else {
                    ElMessage.error('新增失败，请检查数据');
                }
            } catch (err) {
                console.error('新增供应商错误:', err);
                
                // 更详细的错误信息
                if (err.response) {
                console.error("响应数据:", err.response.data);
                ElMessage.error(`新增失败: ${err.response.data.message || err.response.statusText}`);
                } else {
                ElMessage.error(`新增失败: ${err.message}`);
                }
            }
        };

        const Departmentdata = ref([]);
        const Userdata = ref([]);
        const Industrydata = ref([]);
        const Classifydata = ref([]);
        const Supplierydata = ref([]);

        // 查询部门数据
        function GetDepartment() {
            http.get("/Supplier/GetDepartment", {
                params: {
                    Department_id: name
                }
            }).then(res => {
                console.log("API数据:", res.data); // 调试用
                Departmentdata.value = res.data; // 将查询结果赋值给 Departmentdata
            }).catch(err => {
                console.log(err);
                ElMessage.error('数据加载失败');
            });
        }

        // 查询用户数据
        function GetUser() {
            http.get("/Supplier/GetUser", {
                params: {
                    Department_id: name
                }
            }).then(res => {
                console.log("API数据:", res.data); // 调试用
                Userdata.value = res.data; // 将查询结果赋值给 Userdata
            }).catch(err => {
                console.log(err);
                ElMessage.error('数据加载失败');
            });
        }

        // 查询字典数据
        function GetDictData(zd) {
            http.get("/Supplier/GetDictData", {
                params: {
                    dict_id: zd
                }
            }).then(res => {
                console.log("API数据:", res.data); // 调试用
                if (zd === 10) {
                    Classifydata.value = res.data; // 将查询结果赋值给 Classifydata
                } else if (zd === 12) {
                    Industrydata.value = res.data; // 将查询结果赋值给 Industrydata
                }
            }).catch(err => {
                console.log(err);
                ElMessage.error('数据加载失败');
            });
        }

        // 查询Id查供应商数据
        function GetIdSupplier() {
            http.get("/Supplier/GetIdSupplier", {
                params: {
                    id: id.value
                }
            }).then(res => {
                const apiData = res.data; 
                console.log("ID供应商:", apiData); // 调试用
                Object.assign(supplierForm, {
                sup_code: apiData.sup_code || "",
                sup_name: apiData.sup_name || "",
                sup_industry: apiData.sup_industry || "",
                sup_type: apiData.sup_type || "",
                sup_linkman: apiData.sup_linkman || "",
                sup_linkphone: apiData.sup_linkphone || "",
                sup_email: apiData.sup_email || "",
                sup_depId: apiData.sup_depId || null,
                sup_userId: apiData.sup_userId || null,
                sup_status: apiData.sup_status || 0,
                sup_address: apiData.sup_address || "",
                remark: apiData.remark || "",
                sup_accountName: apiData.sup_accountName || "",
                sup_taxpayerNum: apiData.sup_taxpayerNum || "",
                sup_bankAccount: apiData.sup_bankAccount || "",
                sup_openBank: apiData.sup_openBank || "",
                sup_openBankAddress: apiData.sup_openBankAddress || "",
                create_name: sessionStorage.getItem('username') || "" // 从sessionStorage获取
            });
            GetPurchaseFileByCode(supplierForm.sup_code)
            }).catch(err => {
                console.log(err);
                ElMessage.error('数据加载失败');
            });
        }

        async function UpdateSupplier() {
          // 备份原始附件列表
          const originalFileList = [...filelist.value];

          try {
            // 准备更新数据
            const deptObj = Departmentdata.value.find(item => item.department_id === supplierForm.sup_depId);
            const userObj = Userdata.value.find(item => item.user_id === supplierForm.sup_userId);
            const user = JSON.parse(sessionStorage.getItem("user")) || {};

            const updateSupplierDto = {
              sup_id: Number(id.value),
              sup_name: supplierForm.sup_name || "",
              sup_industry: supplierForm.sup_industry,
              sup_type: supplierForm.sup_type || "",
              sup_linkman: supplierForm.sup_linkman || "",
              sup_linkphone: supplierForm.sup_linkphone || "",
              sup_email: supplierForm.sup_email || "",
              sup_depId: Number(supplierForm.sup_depId) || 0,
              sup_depName: deptObj?.department_name || "",
              sup_userId: Number(supplierForm.sup_userId) || 0,
              sup_userName: userObj?.user_name || "",
              sup_status: Number(supplierForm.sup_status) || 0,
              sup_address: supplierForm.sup_address || "",
              remark: supplierForm.remark || "",
              sup_accountName: supplierForm.sup_accountName || "",
              sup_taxpayerNum: supplierForm.sup_taxpayerNum || "",
              sup_bankAccount: supplierForm.sup_bankAccount || "",
              sup_openBank: supplierForm.sup_openBank || "",
              sup_openBankAddress: supplierForm.sup_openBankAddress || "",
              update_name: user?.name || "系统管理员"
            };

            console.log("用户信息", updateSupplierDto);

            // 1. 删除旧附件
            await http.delete("/PublicFile/DeleteFile?type=供应商&code=" + supplierForm.sup_code);

            // 2. 上传新附件
            if (filelist.value.length > 0) {
              for (const file of filelist.value) {
                await http.post("/PublicFile/AddFile?type=供应商&code=" + supplierForm.sup_code + "&file=" + file.url + "&title=" + file.originalName);
              }
            }

            // 3. 更新供应商信息
            const res = await http.put("/Supplier/UpdateSupplier", updateSupplierDto);

            if (res.data > 0) {
              ElMessage.success('供应商更新成功');
              const Detail = ref(route.query ? route.query.Detail || false : false);
              if (Detail.value) {
                router.push({ path: 'supplierdetail', query: { id: id.value } });
              } else {
                router.push('supplier');
              }
            } else {
              ElMessage.error('更新失败，请检查数据');
              filelist.value = originalFileList; // 恢复原始附件列表
            }

          } catch (err) {
            console.error('更新供应商失败:', err);

            let errorMsg = '更新失败';

            if (err.response) {
              console.error("响应状态:", err.response.status);
              console.error("响应数据:", err.response.data);

              if (err.response.data) {
                if (typeof err.response.data === 'string') {
                  errorMsg += `: ${err.response.data}`;
                } else if (err.response.data.message) {
                  errorMsg += `: ${err.response.data.message}`;
                }
              }
            } else if (err.request) {
              errorMsg += ': 服务器无响应';
            } else {
              errorMsg += `: ${err.message}`;
            }

            ElMessage.error(errorMsg);
            filelist.value = originalFileList; // 恢复原始附件列表
          }
        }

        // 验证规则
        const rules = {
          sup_code: [
          {
            required: true,
            validator: (rule, value, callback) => {
              callback();
            },
            trigger: 'blur' 
          }
        ],
          sup_name: [
            { required: true, message: '供应商名称不能为空', trigger: 'blur' }
          ]
        };


        async function save() {
          try {
            // 验证基础信息表单
            await formRef.value.validate();
            // 验证财务信息表单
            await financeFormRef.value.validate();
            
            if (isEdit.value) {
              await UpdateSupplier();
            } else {
              await addSupplier();
            }
          } catch (error) {
            ElMessage.warning('请检查表单中的必填项');
          }
        }

        // 添加地图相关数据
        const showMap = ref(true); // 修改为默认显示
        const map = ref(null);
        const AMap = ref(null);
        let marker = null;
        
        // 初始化地图
        const initMap = async () => {
          try {
            // 确保AMapLoader已加载
            if (!window.AMapLoader) {
              await loadAMapScript();
              return; // 脚本加载后会重新调用initMap
            }
            
            //设置高德地图安全配置
            window._AMapSecurityConfig = {
              securityJsCode: '4dcb3c9d954a6fd243c39d7799671919',
            };
            
            //加载高德地图JS API
            AMap.value = await window.AMapLoader.load({
              key: '6032de26a8237ac7ce5f0a05d229a150',
              version: '2.0',
              plugins: ['AMap.Geolocation', 'AMap.Geocoder', 'AMap.PlaceSearch', 'AMap.Driving']//插件
            });
            
            //创建地图实例
            map.value = new AMap.value.Map('container', {
              zoom: 11, //初始缩放级别
              center: [112.982279, 28.19409], //初始中心点位置
              willReadFrequently: true //频繁读取地图数据时优化性能
            });
            
            
            // 如果有地址，立即搜索
            if (supplierForm.sup_address) {
              setTimeout(() => {
                geocodeAddress();
              }, 500);
            }
          } catch (error) {
            console.error('初始化地图失败:', error);
            ElMessage.error('初始化地图失败，请刷新重试');
          }
        };
        
        // 加载高德地图Loader脚本
        const loadAMapScript = () => {
          return new Promise((resolve, reject) => {
            const script = document.createElement('script');
            script.src = 'https://webapi.amap.com/loader.js';
            script.async = true;
            script.onload = () => resolve();
            script.onerror = () => {
              console.error('加载高德地图API失败');
              ElMessage.error('加载地图API失败，请检查网络');
              reject(new Error('加载高德地图API失败'));
            };
            document.head.appendChild(script);
          });
        };
        
        // 根据地址搜索位置
        function searchAddress() {
          if (!supplierForm.sup_address) {
            ElMessage.warning('请先输入地址');
            return;
          }
          
          showMap.value = true;
          
          // 确保DOM已经渲染并初始化地图
          setTimeout(async () => {
            if (!map.value) {
              await initMap();
            } else {
              geocodeAddress();
            }
          }, 100);
        }
        
        // 地理编码
        function geocodeAddress() {
          if (!AMap.value || !map.value) {
            ElMessage.error('地图组件未加载完成，请稍后再试');
            return;
          }
          
          // 创建地理编码实例
          const geocoder = new AMap.value.Geocoder({
            city: "全国", // 城市设为全国
          });
          
          // 地理编码
          geocoder.getLocation(supplierForm.sup_address, function(status, result) {
            if (status === 'complete' && result.info === 'OK') {
              // 获取第一个地理编码信息
              const geocode = result.geocodes[0];
              const location = geocode.location;
              
              // 设置地图中心点
              map.value.setCenter(location);
              
              // 清除已有标记
              if (marker) {
                map.value.remove(marker);
              }
              
              // 添加标记
              marker = new AMap.value.Marker({
                position: location,
                map: map.value,
                animation: "AMAP_ANIMATION_DROP"
              });
              
              // 创建信息窗体
              const infoWindow = new AMap.value.InfoWindow({
                content: `<div style="padding: 10px;">
                  <h4 style="margin: 0 0 5px 0;">${supplierForm.sup_name || '供应商'}</h4>
                  <p style="margin: 0;">${geocode.formattedAddress}</p>
                </div>`,
                offset: new AMap.value.Pixel(0, -30)
              });
              
              // 添加点击事件打开信息窗体
              marker.on('click', () => {
                infoWindow.open(map.value, location);
              });
              
              // 自动打开信息窗体
              infoWindow.open(map.value, location);
              
              ElMessage.success('地址定位成功');
            } else {
              console.error('地理编码失败:', result);
              ElMessage.warning('无法解析该地址，请尝试更详细的地址');
            }
          });
        }
        
        // 组件销毁时清理资源
        onUnmounted(() => {
          if (map.value) {
            map.value.destroy();
          }
        });

        onMounted(async () => {
            GetDepartment()//部门
            GetUser()//用户
            GetDictData(10)//行业
            GetDictData(12)//分类
            if(isEdit){
                GetIdSupplier()
            }
            
            // 页面加载时立即初始化地图
            setTimeout(async () => {
                await initMap();
            }, 500);
        });

        function jump() {
            router.back();
        }
        
        return {
            handleRemove,
            supplierForm,
            addSupplier,
            save,
            Departmentdata,
            Userdata,
            Industrydata,
            Classifydata,
            Supplierydata,
            isEdit,
            formRef,
            financeFormRef,
            rules,
            jump,
            fileInput,
            filelist,
            handleFileSuccess,
            handlePreview,
            headers,
            showMap,
            searchAddress
        };
    }
}
</script>
  
<style scoped>
    html, body {
        margin: 0;
        padding: 0;
        width: 100%;
        min-width: 100%;
        box-sizing: border-box;
        font-family: 'Segoe UI', 'Microsoft YaHei', sans-serif;
        background-color: #f3f6f8;
        padding: 20px;
    }

    /* 添加错误提示样式 */


    /* 白色圆角容器 - 核心样式 */
    .white-container {
        background: white;
        border-radius: 12px;
        margin-bottom: 50px;
        box-shadow: 0 3px 10px rgba(0, 0, 0, 0.05);
        width: 70%;
    }
    /* 调整网格容器 */
    .grid-container {
    padding: 25px;
    }

    /* 标题左对齐 */
    .section-header {
        grid-column: span 12;
        padding-bottom: 15px;
        margin-bottom: 20px;
        border-bottom: 1px solid #e6e6e6;
        font-size: 18px;
        font-weight: 600;
        color: #2c3e50;
        text-align: left; /* 新增 */
    }

    
    .file-list {
        grid-column: span 12;
        margin-top: 20px;
        list-style: none;
        /* 强制左对齐 */
        text-align: left;
        /* 重置浏览器默认样式 */
        padding-left: 0;
    }
    
    .form-input {
        grid-column: span 6; /* 每个输入框占5列 */
        margin-bottom: 20px;
    }
    .form-input.full {
        grid-column: span 12;
        margin: 20px 0;
    }

    
    
    /* 上传附件 */
    .upload-section {
        grid-column: span 12;
        margin-top: 20px;
        display: flex;
        align-items: center;
        gap: 10px;
    }

    .upload-btn {
        background: #3a7bd5;
        color: white;
        border: none;
        padding: 8px 15px;
        border-radius: 4px;
        cursor: pointer;
    }
    .upload-tips {
        color: #666;
        margin-top: 5px;
        font-size: 13px;
    }
    
    .file-item {
        display: flex;
        justify-content: space-between;
        align-items: center;
        padding: 8px 0;
        border-bottom: 1px solid #f1f1f1;
        /* 防止 flex 子元素自动拉伸 */
        width: 100%;
    }
    .file-name {
        flex: 1;
        margin-right: 15px;
    }
    .delete-icon {
        color: #3a7bd5;
        cursor: pointer;
    }
    
    /* 底部操作栏自适应 */
    .action-bar {
        position: fixed;
        bottom: 0;
        right: 0.5%; /* 与表单右侧对齐 */
        left: 210px; /* 与菜单栏宽度一致 */
        background: white;
        border-top: 1px solid #e6e6e6;
        padding: 15px;
        text-align: right;
    }
    

    /* 调整单选组垂直居中 */
    .el-radio-group {
        display: flex;
        align-items: center;
    }

    .action-btn {
        border: none;
        padding: 8px 20px;
        border-radius: 4px;
        cursor: pointer;
        margin-left: 10px;
    }
    .btn-close {
        background: #f4f4f5;
        color: #666;
    }
    .btn-save {
        background: #3a7bd5;
        color: white;
    }
    .btn-save-add {
        background: #38c172;
        color: white;
    }
</style>